package com.ifacebox.client.tools;

import org.apache.poi.poifs.filesystem.FileMagic;

import javax.swing.*;
import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * @author znn
 */
public class SspUtils {
    private static final URL URL_PATH = SspUtils.class.getProtectionDomain().getCodeSource().getLocation();
    private static final String URL_JAR = ".jar";

    public static String getLocalPath() {
        return getLocalPathFile().getAbsolutePath();
    }

    public static File getLocalPathFile() {
        String path;
        try {
            path = URLDecoder.decode(URL_PATH.getPath(), SspConstants.UTF_8);
        } catch (Exception e) {
            path = URL_PATH.getPath();
        }
        if (path.endsWith(URL_JAR)) {
            path = path.substring(0, path.lastIndexOf("/") + 1);
        }
        return new File(path);
    }

    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (Exception e) {
            //
        }
    }

    public static boolean isExcel(File file) {
        if (file == null || !file.isFile() || !file.exists()) {
            return false;
        }
        try {
            FileMagic fileMagic = FileMagic.valueOf(file);
            return Objects.equals(fileMagic, FileMagic.OLE2)
                    || Objects.equals(fileMagic, FileMagic.OOXML);
        } catch (Exception e) {
            return false;
        }
    }

    public static void runThread(Runnable run, String name) {
        (new Thread(run, name) {{
            this.setDaemon(true);
        }}).start();
    }

    public static Box addFieldBox(String label, JComponent field) {
        return new Box(BoxLayout.X_AXIS) {{
            this.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
            this.add(new JLabel(label));
            this.add(field);
        }};
    }
}
